package org.jprogger.myworld.app.auth;

import javax.servlet.http.HttpServletRequest;

import org.jprogger.myworld.app.auth.model.AppPermission;
import org.jprogger.myworld.app.auth.model.AppUser;
import org.jprogger.myworld.app.auth.model.AppWindow;
import org.jprogger.myworld.app.auth.model.Application;
import org.jprogger.myworld.app.auth.model.UserAuth;
import org.jprogger.myworld.app.auth.model.UserRole;

public class AppUserFactory {

	private static AppUserFactory instance;
	
	private AppUserFactory(){}
	
	public static AppUserFactory getInstance(){
		if (instance == null) 
		{
			instance = new AppUserFactory();
		}
		return instance;
		
	}
	
	private UserAuth createUserAuth(HttpServletRequest request) {
		
		UserAuth auth = null;
		String authKey = request.getParameter("authentication_key");
		String sessionKey = request.getParameter("session_key");
		auth = new UserAuth(sessionKey, authKey);
		return auth;
	}
	
	private UserRole createUserRole(HttpServletRequest request) {
		
		UserRole role = null;
		String ownerId = request.getParameter("oid");
		String viewerId = request.getParameter("vid");
		String isAppUser = request.getParameter("is_app_user");
		role = new UserRole(Integer.parseInt(ownerId), Integer.parseInt(viewerId), Boolean.parseBoolean(isAppUser));
		return role;
	}
	
	private AppPermission createAppPermissions(HttpServletRequest request) {
		AppPermission permission = null;
		String appPermission = request.getParameter("ext_perm");
		String[] perm = appPermission.split(",");
		permission = new AppPermission(perm);
		return permission;
	}
	
	private AppWindow createAppWindow(HttpServletRequest request) {
		AppWindow window = null;
		String appWindowId 	 = request.getParameter("window_id");
		window = new AppWindow(Integer.parseInt(appWindowId));
		return window;
	}
	
	private Application createApp(HttpServletRequest request, AppPermission perm, AppWindow wind) {
		Application app = null;
		String appId = request.getParameter("app_id");
		String appState = request.getParameter("state");
		app = new Application(Integer.parseInt(appId), appState, wind, perm);
		return app;
	}
		
	public AppUser createAppUser(HttpServletRequest request) {
		
		AppUser user = null;
		UserRole role = createUserRole(request);
		UserAuth auth = createUserAuth(request);
		AppWindow window = createAppWindow(request);
		AppPermission permission = createAppPermissions(request);
		Application application = createApp(request, permission, window);
		user = new AppUser(role, auth, application);
		return user;
	}
}
